﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Ventigrate.Shared.PermissiveXFrameHeader.Extensions;

namespace Ventigrate.Shared.PermissiveXFrameHeader.Modules
{
    public class PermissiveXFrameHeaderModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication app)
        {
            app.BeginRequest += app_AllowFraming;
            app.EndRequest += app_AllowFraming;
        }

        protected void app_AllowFraming(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            AllowFraming(context);
        }

        private void AllowFraming(HttpContext context)
        {
            try
            {
                // General requests -- exclude AppRedirect page which adds the same element but doesn't properly check if alreay added!
                if (!context.Items.Contains("AllowFraming") && !context.Request.IsAppRedirect())
                {
                    context.Items.Add("AllowFraming", String.Empty);
                }

                // IPFS requests
                if (!context.Items.Contains("FrameOptionsHeaderSet"))
                    context.Items.Add("FrameOptionsHeaderSet", String.Empty);

                // XLViewer
                context.Response.Headers.Remove("X-FRAME-OPTIONS");
            }
            catch { }
        }
    }
}
